<?php

namespace App\Http\Controllers\H5;

use App\Models\UserRelation;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\User;

class TeamController extends BaseController
{

    public function index()
    {

        $upuids = UserRelation::where('upuid', $this->uid)->get()->map(function ($relation){
            return $relation->uid;
        });
        $count1 = $upuids->count();
        $count2 = UserRelation::whereIn('upuid', $upuids)->count();

        return $this->view('h5.team.index', compact('count1','count2'));
    }

    public function geteamlist()
    {
        $offset = $this->request->input('offset');
        $count  = $this->request->input('count');
        $offset = $offset ? $offset : 0;
        $count  = $count ? $count : 20;
        $tradeStatus = $this->request->input('tradeStatus');
        $uid = $this->uid;
        $firstusers = User::where('puid',$uid)->get();
        if($tradeStatus==0)
        {
          return $firstusers;
        }else
        {
        $fuid = '';
        if(!empty($firstusers))
        {
            foreach ($firstusers as $fusers=>$user)
            {
                $fuid.=$user['uid'].',';

            }
            $firstusers= null;
      }
      if($fuid !='')
      {
        $fuid = substr($fuid, 0, strlen($fuid)-1);
        $secusers =  User::wherein('puid', explode(',', $fuid))->get();
      }else
      {
          $secusers = null;
      }

      return $secusers;
    }
 }

    public function getUsers(Request $request)
    {
        $offset = $request->input('offset', 0);
        $count  = $request->input('count', 10);
        $level  = $request->input('level', 1);

        if ($level == 1)
        {
            $users = UserRelation::with('user')->whereHas('user')->where('upuid', $this->uid)
                ->offset($offset)->limit($count)->orderByDesc('created_at')
                ->get()->map(function ($relation){
                    return $relation->user;
                });
            return ajaxReturn(['users'=>$users]);
        }

        if ($level == 2)
        {
            $upuids = UserRelation::where('upuid', $this->uid)->get()->map(function ($relation){
                return $relation->uid;
            });

            $users = UserRelation::with('user')->whereHas('user')->whereIn('upuid', $upuids)
                ->offset($offset)->limit($count)->orderByDesc('created_at')
                ->get()->map(function ($relation){
                    return $relation->user;
                });
            return ajaxReturn(['users'=>$users]);
        }

        return ajaxReturn(['users'=>[]]);
    }
}
